import axios from "axios";
import { ElMessageBox, ElMessage } from "element-plus";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { getCurrentOrg } from "./auth";
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url =  url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation

      config.headers["Authorization"] = getToken();
      config.headers["ORG"] = getCurrentOrg();
    }

    // 这个应该本项目没用
    // if (store.state.user.currentRole) {
    //   config.headers['OrgRoleId'] = store.state.user.currentRole
    // }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug

    return Promise.reject(error);
  }
);

// 下载接口白名单
const whiteList = ["/svc/version/jar/download"];
function isWhiteList(url) {
  return whiteList.includes(url);
}
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    // if the custom code is not 200, it is judged as an error.
    if (res.status !== 200 && res.status !== 201) {
      ElMessage({
        message: res.message || "数据异常，请联系管理员 R",
        type: "error",
        duration: 5 * 1000,
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 401 || res.status === 403) {
        // to re-login
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
      }
    }
    return res;
  },
  (error) => {
    console.log("errorerrorerrorerrorerrorerror");
    const arr = error.response.config.url.split(error.response.config.baseURL);
    const message = error.response.data.message;
    ElMessage({
      message:
        message ? message:
        error.response.status === 401 ||
        error.response.status === 403 
          ? "您没有角色权限，请联系管理员"
          : "数据异常，请联系管理员 E",
      type: "error",
    });
    if (error.response.status > 500 || error.response.status === 401 || error.response.status === 403) {
      setTimeout(() => {
        store.dispatch("user/resetToken").then(() => {
          // localStorage.setItem("tip", "当前用户无权限，请联系管理员");
          location.reload();
        });
      }, 1500)
      
    }
    return Promise.reject(error);
  }
);

export default service;
